package com.tb.education.server;

import com.tb.education.common.packets.DevicePacket;
import com.tb.education.common.packets.MsgWrapper;
import org.tio.core.ChannelContext;
import org.tio.core.GroupContext;
import org.tio.core.exception.AioDecodeException;
import org.tio.core.intf.Packet;
import org.tio.server.intf.ServerAioHandler;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.util.Objects;

/**
 * 消息处理抽象类
 *
 * @author wangze
 * @date 2020-07-08 14:37.
 **/

public abstract class ServerAbsMsgHandler implements ServerAioHandler {
	/**
	 * 解密
	 *
	 * @param buffer
	 * @param limit
	 * @param position
	 * @param readableLength
	 * @param channelContext
	 * @return
	 * @throws AioDecodeException
	 */
	@Override
	public DevicePacket decode(ByteBuffer buffer, int limit, int position, int readableLength, ChannelContext channelContext) throws AioDecodeException {
		DevicePacket imPacket = new DevicePacket();
		byte[] dst = new byte[readableLength];
		buffer.get(dst, position, readableLength);
		imPacket.setBody(dst);
		try {
			MsgWrapper wrapper = DevicePacket.parseByte(dst);
			if (Objects.isNull(wrapper)) {
				return null;
			}
			imPacket.setOperationType(wrapper.getHead().getOperationType());
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return null;
		}


		return imPacket;

	}

	/**
	 * @param packet
	 * @param groupContext
	 * @param channelContext
	 * @return
	 */
	@Override
	public ByteBuffer encode(Packet packet, GroupContext groupContext, ChannelContext channelContext) {
		DevicePacket devicePacket = (DevicePacket) packet;
		byte[] body = devicePacket.getBody();
		int bodyLen = 0;
		if (body != null) {
			bodyLen = body.length;
		}
		//创建一个新的bytebuffer
		ByteBuffer buffer = ByteBuffer.allocate(bodyLen);
		//设置字节序
		buffer.order(groupContext.getByteOrder());
		//写入消息体
		if (body != null) {
			buffer.put(body);
		}
		return buffer;
	}
}
